package org.store;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE;

public class ScriptRunner implements ApplicationContextAware {
    private ApplicationContext ctx;
    private SimpleJdbcTemplate template;
    private String directory;

    private final AtomicBoolean finished = new AtomicBoolean();

    @Transactional
    public void runScripts() throws IOException {
        File sqlDir = ResourceUtils.getFile("classpath:" + directory);
        Collection<File> files = FileUtils.listFiles(sqlDir, TRUE, TRUE);
        for (File each : files) {
            executeSqlScript(directory + "/" + each.getName());
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void sql(String sql) {
        template.update(sql);
    }

    protected void executeSqlScript(String sqlResourcePath) throws DataAccessException {
        Resource resource = this.ctx.getResource(sqlResourcePath);
        SimpleJdbcTestUtils.executeSqlScript(this.template, new EncodedResource(resource, "utf-8"), false);
    }

    @Autowired
    public void setDataSource(DataSource dataSource) {
        template = new SimpleJdbcTemplate(dataSource);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }
}
